<template>
	<div class="wrapper">
		<div class="top">
			<div class="top_control">
				<el-date-picker
				v-model="top_selct_date"
				type="date"
				placeholder="请选择日期"
				value-format="YYYY-MM-DD"
				@change="resetTopData"></el-date-picker>
			</div>
			<div class="top_echart"><ECharts :options="chartOptions_top" /></div>
		</div>
		<div class="bottom">
			<div class="left">
				<div class="left_control">
					<el-button  v-if="leftIsMap" @click="setLeftBar_click">年平均收入柱状图</el-button>
					<el-button  v-if="!leftIsMap" @click="setLeftMap_click">贫困户地区分布</el-button>
					<el-button  @click="resetLeftData">更新数据</el-button>
				</div>
				<div class="left_echart">
					<ECharts v-if="mapLoaded" :options="chartOptions_left" />
				</div>
			</div>
			<div class="right">
				<div class="right_control">
					<el-date-picker
					v-model="right_start"
					type="date"
					placeholder="请选择起始日期"
					value-format="YYYY-MM-DD"
					@change="resetRightData"></el-date-picker>
					<el-date-picker
					v-model="right_end"
					type="date"
					placeholder="请选择终止日期"
					value-format="YYYY-MM-DD"
					@change="resetRightData"></el-date-picker>
				</div>
				<div class="right_echart">
					<ECharts :options="chartOptions_right" />
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {ref,onMounted,reactive,watch} from 'vue';
	import ECharts from '@/echarts/echarts.vue';
	import * as echarts from 'echarts';
	import {get} from '@/axios';
	import { userAreaStore } from '@/stores';
	const areaStore = userAreaStore()
	// 将 areaStore.userArea 转换为字符串类型
	let areaId = areaStore.userArea.toString();
	
	// 如果地区编码大于4位，只保留前4位
	if (areaId.length > 4) {
	  areaId = areaId.slice(0, 4);
	}
	
	// 对 mapId 进行处理，确保其始终为6位
	let mapId = areaStore.userArea.toString();
	if (mapId.length > 6) {
	  mapId = mapId.slice(0, 6);
	} else if (mapId.length < 6) {
	  mapId = mapId.padEnd(6, '0'); // 不足6位用0补全
	}

	
	const leftIsMap = ref(true);
	
	const map = mapId;
	const mapLoaded = ref(false);
	const rid = areaId;
	
	const left_data_map = ref([]);
	const left_title = ref('');
	const left_legend = ref('');
	const left_datamax = ref();
	const left_data_bar = ref([]);
	const left_categories = ref([]);
	
	const top_data = ref([]);
	const top_date = ref([]);
	const top_selct_date = ref('');
	
	const right_start = ref('');
	const right_end = ref('');
	
	const chartOptions_left = ref({
		title: {
			text: "waitting for data",
			left: 'left',
		},
		toolbox: {
			show: true,
			left: 'right',
			top: 'top',
			feature: {
				dataView: {
					readOnly: true,
				},
				restore: {},
				saveAsImage: {},
			},
		},
		tooltip: {
			trigger: 'item',
			formatter: function(params) {
				const seriesName = params.seriesName;
				const name = params.name;
				if (params.data) {
					const value = params.value;
					return `${seriesName}<br/>${name}：${value}`;
				} else {
					return `${seriesName}<br/>${name}：无数据`;
				}
			},
		},
		legend: {
			show: false,
		},
		visualMap: {
			left: 'right',
			min: 0,
			max: 1000,
			text: ['高', '低'],
			calculable: true,
			inRange: {
				color: ['green', 'yellow', 'red'],
				symbolSize: [100, 100],
			},
		},
		series: [{
			name: "waitting for data",
			type: 'map',
			map: 'map',
			roam: true,
			nameProperty: 'name',
			data: [],
			itemStyle: {
				normal: {
					color: 'rgba(0, 0, 0, 0)',
				},
				emphasis: {
					color: 'rgba(0, 0, 0, 0)',
				},
			},
		}, ],
	});
	
	const chartOptions_top = ref({
		title: {
		    text: '之前七天的采访记录数量'
		},
		tooltip: {
		    trigger: 'axis'
		},
		xAxis: {
		    type: 'category',
		    data: ['waiting', 'waiting', 'waiting', 'waiting', 'waiting', 'waiting', 'waiting']
		},
		yAxis: {
		    type: 'value'
		},
		series: [
		    {
		        data: [0, 0, 0, 0, 0, 0, 0],
		        type: 'line'
		    }
		]
	});
	
	const chartOptions_right = ref({
		dataset: [
		    {
		      dimensions: ['name', 'count'],
		      source: [
		        ['waiting', 0]
		      ]
		    },
		    {
		      transform: {
		        type: 'sort',
		        config: { dimension: 'count', order: 'desc' }
		      }
		    }
		  ],
		  yAxis: {
		    type: 'category',
		    axisLabel: { interval: 0 }
		  },
		  xAxis: {
			  type: 'value',
		  },
		  series: {
		    type: 'bar',
		    encode: { x: 'count', y: 'name' },
		    datasetIndex: 1
		  }
	})
	
	const setLeftMap_click = async () => {
		get('/data/count', {rId: rid}, (content) => {
			left_data_map.value = content.data;
			left_title.value = content.title;
			left_legend.value = content.legend;
			left_datamax.value = content.datamax;
			setLeftMap()
		});
	}
	
	const setLeftBar_click = async () => {
		get('/data/avgincome',{rId: rid}, (content) => {
			left_data_bar.value = content.data;
			left_categories.value = content.categories;
			left_title.value = content.title;
			left_legend.value = content.legend;
			setLeftBar()
		});
	}
	
	const resetLeftData = async () => {
		if(leftIsMap.value){
			resetLeftData_Map();
		}else{
			resetLeftData_Bar();
		}
	}
	
	const setLeftMap = async () => {
		chartOptions_left.value = {
			title: {
				text: left_title.value,
				left: 'left',
			},
			toolbox: {
				show: true,
				left: 'right',
				top: 'top',
				feature: {
					dataView: {
						readOnly: true,
					},
					restore: {},
					saveAsImage: {},
				},
			},
			tooltip: {
				trigger: 'item',
				formatter: function(params) {
					const seriesName = params.seriesName;
					const name = params.name;
					if (params.data) {
						const value = params.value;
						return `${seriesName}<br/>${name}：${value}`;
					} else {
						return `${seriesName}<br/>${name}：无数据`;
					}
				},
			},
			legend: {
				show: false,
			},
			visualMap: {
				left: 'right',
				min: 0,
				max: left_datamax.value,
				text: ['高', '低'],
				calculable: true,
				inRange: {
					color: ['green', 'yellow', 'red'],
					symbolSize: [100, 100],
				},
			},
			series: [{
				name: left_legend.value,
				type: 'map',
				map: 'map',
				roam: true,
				nameProperty: 'name',
				data: left_data_map.value,
				itemStyle: {
					normal: {
						color: 'rgba(0, 0, 0, 0)',
					},
					emphasis: {
						color: 'rgba(0, 0, 0, 0)',
					},
				},
			}, ],
		}
		leftIsMap.value = true;
	};
	
	const setLeftBar = async () => {
		chartOptions_left.value = {
			title: {
				text: left_title.value,
				left: 'center',
			},
			tooltip: {},
			toolbox: {},
			legend: {
				data: left_legend.value,
			},
			dataZoom: [{
					type: 'slider',
					show: true,
					start: 0,
					end: 20,
					handleSize: 20,
				},
				{
					type: 'inside',
					start: 0,
					end: 2,
				},
			],
			visualMap:{
				show: false,
			},
			xAxis: {
				type:'category',
				data: left_categories.value,
				axisTickObject:{
					alignWithLabel:true,
					interval:0
				}
			},
			yAxis: {},
			series: [{
				name: left_legend.value,
				type: 'bar',
				data: left_data_bar.value,
			}, ],
		}
		leftIsMap.value = false;
	}
	
	const resetLeftData_Map = async () => {
		get('/data/count', {rId: `${rid}`}, (content) => {
			left_data_map.value = content.data;
			left_title.value = content.title;
			left_legend.value = content.legend;
			left_datamax.value = content.datamax;
			chartOptions_left.value.series[0].data = left_data_map.value;
			chartOptions_left.value.title.text = left_title.value;
			chartOptions_left.value.visualMap.max = left_datamax.value;
			chartOptions_left.value.series[0].name = left_legend.value;
		});
	}
	
	const resetLeftData_Bar = async () => {
		get('/data/avgincome',{rId: `${rid}`}, (content) => {
			left_data_bar.value = content.data;
			left_categories.value = content.categories;
			left_title.value = content.title;
			left_legend.value = content.legend;
			chartOptions_left.value.series[0].data = left_data_bar.value;
			chartOptions_left.value.title.text = left_title.value;
			chartOptions_left.value.xAxis.data = left_categories.value;
			chartOptions_left.value.series[0].name = left_legend.value;
			chartOptions_left.value.legend.data = left_legend.value;
		});
	}
	
	const resetTopData = async () => {
		get('/data/resentinterview',{rId: `${rid}`,today: top_selct_date.value},(content) => {
			top_data.value = content.data;
			top_date.value = content.categories;
			chartOptions_top.value.xAxis.data = top_date.value;
			chartOptions_top.value.series[0].data = top_data.value;
		});
		
	}
	
	const resetRightData = async () => {
		get('/data/admininterview',{rId:rid,startDate:right_start.value,endDate:right_end.value},(content) => {
			chartOptions_right.value.dataset[0].source = content;
			console.dir(content);
		})
	}
	
	const loadMapData = async () => {
		try {
			const module = await import(`@/maps/${map}.json`);
			const Map = module.default;
			echarts.registerMap('map', Map);
			mapLoaded.value = true; // Set mapLoaded to true when map is registered
		} catch (error) {
			console.error('Failed to load map data:', error);
		}
	};
	
	function getFormattedDate() {
	  const today = new Date();
	  const year = today.getFullYear();
	  const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1
	  const day = String(today.getDate()).padStart(2, '0');
	  
	  return `${year}-${month}-${day}`;
	}
	
	const setRightDate = async () => {
		right_start.value = getFormattedDate();
		right_end.value = getFormattedDate();
	}
	
	const setTopDate = async () => {
		top_selct_date.value = getFormattedDate();
	}
	
	onMounted(() => {
		get('/data/count', {rId:rid}, (content) => {
			left_data_map.value = content.data;
			left_title.value = content.title;
			left_legend.value = content.legend;
			left_datamax.value = content.datamax;
			loadMapData();
			setLeftMap();
		});
		setRightDate();
		resetRightData();
		setTopDate();
		resetTopData();
	});
</script>

<style scoped lang="scss">
	$MyBorder: 1px solid #cccccc;

	.wrapper {
		display: flex;
		flex-direction: column;
		
		.top {
			flex: 9;
			display: flex;
			flex-direction: column;
			
			.top_control {
				height: 30px;
				width: 100%;
			}
			.top_echart {
				flex: 1;
			}
		}

		.bottom {
			margin-top: 0px;
			flex: 3;
			display: flex;

			.left {
				flex: 1;
				border: $MyBorder;
				border-radius: 10px;
				display: flex;
				flex-direction: column;
				justify-content: center;
				/* 水平居中 */
				margin-bottom: 90px;
				display: flex;
				
				.left_control {
					height: 30px;
					width: 100%;
				}
				.left_echart {
					flex: 1;
				}
			}
			.right {
				flex: 1;
				border: $MyBorder;
				border-radius: 10px;
				display: flex;
				flex-direction: column;
				justify-content: center;
				/* 水平居中 */
				margin-bottom: 90px;
				display: flex;
				
				.right_control {
					height: 30px;
					width: 100%;
				}
				.right_echart {
					flex: 1;
				}
			}
		}
	}
</style>